package com.l.web.master.webcontent;

import com.l.web.master.system.webnode.WebNode;
import com.l.web.master.system.webnode.WebNodeDAO;
import com.l.web.master.system.webnode.WebNodeOption;
import com.l.web.master.system.webnode.WebNodeOptionDAO;
import org.l.qiao.Cluster;
import org.l.qiao.Page;
import org.l.qiao.search.Field;
import org.l.qiao.search.Query;
import org.l.qiao.search.Sort;
import org.l.qiao.web.ResponseCode;
import org.l.qiao.web.ServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WebContentService extends ServiceSupport {

    @Autowired
    private WebNodeDAO webNodeDAO;
    @Autowired
    private WebContentDAO webContentDAO;
    @Autowired
    private WebNodeOptionDAO webNodeOptionDAO;

    public List<Cluster> getWebNodes() {
        Field field = new Field();
        field.include(WebNode.NAME, WebNode.PARENT_ID, WebNode.CREATED, WebNode.TYPE);
        Sort sort = new Sort();
        sort.asc(WebNode.INDEX);
        List<Cluster> webNodes = webNodeDAO.find(null, field, sort);
        return webNodes;
    }

    public Cluster getPageList(Page page, WebContent webContent, Cluster field, Cluster sort) {
        Cluster webContentPage = webContentDAO.findPage(webContent, field, sort, page);
        return webContentPage;
    }

    public WebContent getDetail(String id, String webNodeId) {
        Query contentQuery = new Query();
        contentQuery.idEQ(WebContent.WEB_NODE_ID, webNodeId);

        if (id != null) {
            contentQuery.idEQ(id);
        }

        Cluster webContent = webContentDAO.findOne(contentQuery);
        return new WebContent(webContent);
    }

    public List<Cluster> getOptions(String webNodeId) {
        Query optionQuery = new Query();
        optionQuery.idEQ(webNodeId);
        Sort sort = new Sort();
        sort.asc(WebNodeOption.INDEX);
        List<Cluster> webNodeOptions = webNodeOptionDAO.find(optionQuery, null, sort);
        return webNodeOptions;
    }

    public int save(WebContent webContent) {
        String id = webContent.setId();
        webContent.put(WebContent.CREATED, new Date());
        webContent.initWebNodeId();
        webContentDAO.insert(webContent);
        return ResponseCode.FINISH;
    }

    public int remove(List<String> ids) {
        Query query = new Query();
        query.idIn(ids);
        webContentDAO.remove(query);
        return ResponseCode.FINISH;
    }
}
